package com.vf.admin.client.dao;


import com.vf.admin.common.db.BaseDao;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.AppFamily;
import com.vf.admin.miaodong.entity.AppFamilyMember;
import com.vf.admin.miaodong.entity.AppFamilyPrestige;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.utils.StringEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AppFamilyDao extends BaseDao<AppFamily> {

    @Autowired
    private AppFamilyPrestigeDao appFamilyPrestigeDao;
    @Autowired
    private AppFamilyMemberDao appFamilyMemberDao;
    @Autowired
    private AppUserDao appUserDao;


    /**
     * 创建或修改家族
     *
     * @param appFamily
     */
    public void save(AppFamily appFamily) {
        if (appFamily != null && appFamily.getId() != null && appFamily.getId() > 0) {
            this.update(appFamily);
        } else {
            appFamily.setId(this.add(appFamily));
        }
    }


    /**
     * 根据族长id查询
     *
     * @param leaderId
     * @return
     */
    public AppFamily findByLeaderId(Integer leaderId) {
        if (StringEx.isNullOrLing(leaderId)) {
            return null;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");
        stringBuilder.append(" and leaderid = ?");
        stringBuilder.append(" and status = 0");
        params.add(leaderId);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, params, AppFamily.class);
    }

    public AppFamily findByLeaderId1(Integer leaderId) {
        if (StringEx.isNullOrLing(leaderId)) {
            return null;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");
        stringBuilder.append(" and leaderid = ?");
        params.add(leaderId);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, params, AppFamily.class);
    }


    public AppFamily findById(Integer id) {
        if (StringEx.isNullOrLing(id)) {
            return null;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");
        stringBuilder.append(" and status = 0");
        stringBuilder.append(" and id = ?");
        params.add(id);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, params, AppFamily.class);
    }

    public AppFamily findFamilyById(Integer id) {
        if (StringEx.isNullOrLing(id)) {
            return null;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");
//        stringBuilder.append(" and status = 0");
        stringBuilder.append(" and id = ?");
        params.add(id);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, params, AppFamily.class);
    }


    public AppFamily findByIdAll(Integer id) {
        if (StringEx.isNullOrLing(id)) {
            return null;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");
        stringBuilder.append(" and id = ?");
        params.add(id);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, params, AppFamily.class);
    }


    /**
     * 家族成员+1
     *
     * @param id
     */
    public void familyMemberInc(Integer id) {
        if (StringEx.isNull(id)) {
            return;
        }
        String sql = " UPDATE app_family SET familycount = familycount + 1  WHERE id = ?";
        ArrayList<Object> paramList = new ArrayList<Object>();
        paramList.add(id);
        this.update(sql, paramList);
    }

    /**
     * 家族成员-1
     *
     * @param id
     */
    public void familyMemberDec(Integer id) {
        if (StringEx.isNull(id)) {
            return;
        }
        String sql = " UPDATE app_family SET familycount = familycount - 1  WHERE id = ? and familycount>1";
        ArrayList<Object> paramList = new ArrayList<Object>();
        paramList.add(id);
        this.update(sql, paramList);
    }


    public List<AppFamily> getFamilyList(String lon, String lat, Integer shiid, Integer type, Integer userId, SplitPageBean splitPageBean) {
        if (StringEx.isNull(type)) {
            return null;
        }
        if (type == 1) {
            if (StringEx.isNull(shiid)) {
                return null;
            }
        } else if (type == 2) {
            if (StringEx.isNull(lon) || StringEx.isNull(lat)) {
                return null;
            }
        }
        ArrayList<Object> paramList = new ArrayList<Object>();
        String sql = "";
        AppFamilyMember family = appFamilyMemberDao.getFamily(userId);

        switch (type) {
            case 1:
                StringBuilder stringBuilder = new StringBuilder("select * from app_family where 1=1");

                stringBuilder.append(" and addrshi = ?");
                paramList.add(shiid);
                stringBuilder.append(" and status=0");
                if (family != null) {
                    stringBuilder.append(" and id != ?");
                    paramList.add(family.getFid());
                }
                stringBuilder.append(" order by prestigenum desc");
                sql = stringBuilder.toString();
                List<AppFamily> appFamilies = this.queryList(sql, paramList, AppFamily.class, splitPageBean);
                if (appFamilies == null || appFamilies.size() <= 0) {
                    ArrayList<Object> list = new ArrayList<>();
                    String sqls = "select * from app_family where status=0";
                    if (family != null) {
                        sqls += " and id != ?";
                        list.add(family.getFid());
                    }
                    sqls += " order by prestigenum desc";
                    List<AppFamily> appFamilies1 = this.queryList(sqls, list, AppFamily.class, splitPageBean);
                    for (AppFamily family1 : appFamilies1) {
                        int isAddFamily = 2;
                        AppFamilyMember byUserIdAndFid = appFamilyMemberDao.findByUserIdAndFid(userId, family1.getId());
                        if (byUserIdAndFid != null) {
                            if (byUserIdAndFid.getStatus() == 0) {
                                isAddFamily = 0;
                            } else if (byUserIdAndFid.getStatus() == 1) {
                                isAddFamily = 1;
                            }
                        }
                        family1.setIsAddFamily(isAddFamily);
                    }
                    return appFamilies1;
                }
                for (AppFamily family1 : appFamilies) {
                    int isAddFamily = 2;
                    AppFamilyMember byUserIdAndFid = appFamilyMemberDao.findByUserIdAndFid(userId, family1.getId());
                    if (byUserIdAndFid != null) {
                        if (byUserIdAndFid.getStatus() == 0) {
                            isAddFamily = 0;
                        } else if (byUserIdAndFid.getStatus() == 1) {
                            isAddFamily = 1;
                        }
                    }
                    family1.setIsAddFamily(isAddFamily);
                }
                return appFamilies;
            case 2:
                StringBuilder stringBuilder1 = new StringBuilder(" select *,(st_distance(POINT(lon,lat),POINT(?,?))*111195) as mi from app_family where 1=1");
                stringBuilder1.append(" and lon is not null");
                paramList.add(lon);
                paramList.add(lat);
                if (family != null) {
                    stringBuilder1.append(" and id != ?");
                    paramList.add(family.getFid());
                }
                stringBuilder1.append(" order by mi asc");
                sql = stringBuilder1.toString();
                return this.queryList(sql, paramList, AppFamily.class, splitPageBean);
            case 3:
                List<AppFamilyPrestige> dayList = appFamilyPrestigeDao.getDayList(userId);
                List<AppFamily> list = new ArrayList<>();
                if (dayList != null && dayList.size() > 0) {
                    dayList.forEach(e -> {
                        ArrayList<Object> paramListDay = new ArrayList<Object>();
                        StringBuilder stringBuilder6 = new StringBuilder("select * from app_family where id=? and status=0");
                        paramListDay.add(e.getFid());
                        String daySql = stringBuilder6.toString();
                        AppFamily appFamily = this.queryObj(daySql, paramListDay, AppFamily.class);
                        list.add(appFamily);
                    });
                    return list;
                } else {
                    return null;
                }
            case 4:
                List<AppFamilyPrestige> listWeek = appFamilyPrestigeDao.getWeekList(userId);
                List<AppFamily> weeklist = new ArrayList<>();

                if (listWeek != null && listWeek.size() > 0) {
                    listWeek.forEach(e -> {
                        ArrayList<Object> paramListWeek = new ArrayList<Object>();
                        StringBuilder stringBuilder6 = new StringBuilder("select * from app_family where id=? and status=0");
                        paramListWeek.add(e.getFid());
                        String daySql = stringBuilder6.toString();
                        AppFamily appFamily = this.queryObj(daySql, paramListWeek, AppFamily.class);
                        weeklist.add(appFamily);
                    });
                    return weeklist;
                } else {
                    return null;
                }
            case 5:
                StringBuilder stringBuilder5 = new StringBuilder("select * from app_family where 1=1");
                stringBuilder5.append(" and status=0");
                stringBuilder5.append(" order by prestigenum desc");
                sql = stringBuilder5.toString();
                List<AppFamily> appFamilies5 = this.queryList(sql, paramList, AppFamily.class, splitPageBean);
                for (AppFamily family5 : appFamilies5) {
                    int isAddFamily = 2;
                    AppFamilyMember byUserIdAndFid = appFamilyMemberDao.findByUserIdAndFid(userId, family5.getId());
                    if (byUserIdAndFid != null) {
                        if (byUserIdAndFid.getStatus() == 0) {
                            isAddFamily = 0;
                        } else if (byUserIdAndFid.getStatus() == 1) {
                            isAddFamily = 1;
                        }
                    }
                    family5.setIsAddFamily(isAddFamily);
                }
                return appFamilies5;
            default:
                return null;
        }
//        return null;
//        return this.queryList(sql,paramList,AppFamily.class,splitPageBean);
    }

    /**
     * 家族总威望值增加
     *
     * @param fid
     * @param num
     */
    public void prestigeNumInc(Integer fid, Integer num) {
        if (StringEx.isNull(fid)) {
            return;
        }
        String sql = " UPDATE app_family SET prestigenum = prestigenum + ?  WHERE id = ?";
        ArrayList<Object> paramList = new ArrayList<Object>();
        paramList.add(num);
        paramList.add(fid);
        this.update(sql, paramList);
    }

    public void updateFamilyLevel(Integer fid, Integer level) {
        String sql = " update app_family set familylevel=? where id = ?";
        ArrayList<Object> paramList = new ArrayList<Object>();
        paramList.add(level);
        paramList.add(fid);
        this.update(sql, paramList);
    }


    public Integer findRankingByPrestige(Integer fid, Integer type) {
        int a = 0;
        if (type == 1) {
            List<AppFamilyPrestige> dayList = appFamilyPrestigeDao.getDayList();
            for (int i = 0; i < dayList.size(); i++) {
                if (dayList.get(i).getFid() == fid) {
                    a = i + 1;
                    break;
                }
            }
            return a;
        } else if (type == 2) {
            List<AppFamilyPrestige> list = appFamilyPrestigeDao.getWeekList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getFid() == fid) {
                    a = i + 1;
                    break;
                }
            }

            return a;
        } else {
            ArrayList<Object> paramList = new ArrayList<Object>();
            StringBuilder stringBuilder5 = new StringBuilder("select * from app_family where 1=1");
            stringBuilder5.append(" and status=0");
            stringBuilder5.append(" order by prestigenum desc");
            String sql = stringBuilder5.toString();
            List<AppFamily> appFamilies = this.queryList(sql, paramList, AppFamily.class);
            for (int i = 0; i < appFamilies.size(); i++) {
                if (appFamilies.get(i).getId() == fid) {
                    a = i + 1;
                    break;
                }
            }
            return a;
        }
    }


    /*public AppFamily findRankingByPrestige(Integer fid, Integer type) {
        if(StringEx.isNullOrLing(fid)){
            return null;
        }
        List<Object> paramList = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        String asname = "allRanking";
        if(type == 1){
            asname = "dayRanking";
        }else if (type == 2){
            asname = "weekRanking";
        }
        stringBuilder.append("select * from ( select *, ( @rowNum := @rowNum + 1 ) as "+asname+" from app_family, ( select ( @rowNum := 0 ) ) b order by prestigenum desc ) c where");
        stringBuilder.append(" id = ?");
        if(type==1){
            stringBuilder.append(" and to_days(createtime) = to_days(now())");
        }else if(type==2){
            stringBuilder.append(" YEARWEEK( date_format(  createtime,'%Y-%m-%d' ) ) = YEARWEEK( now() )");
        }
        paramList.add(fid);
        String sql = stringBuilder.toString();
        return this.queryObj(sql, paramList, AppFamily.class);

    }*/

    /**
     * 修改家族公告
     *
     * @param id
     * @param familyNotice
     */
    public void saveFamilyNotice(Integer id, String familyNotice) {
        ArrayList<Object> list = new ArrayList<>();
        String sql = "update app_family set familynotice=? where id=?";
        list.add(familyNotice);
        list.add(id);
        this.update(sql, list);
    }

    /**
     * 修改家族头像
     *
     * @param id
     * @param pic
     */
    public void saveUploadPic(Integer id, String pic) {
        ArrayList<Object> list = new ArrayList<>();
        String sql = "update app_family set pic=? where id=?";
        list.add(pic);
        list.add(id);
        this.update(sql, list);
    }

    /**
     * 修改家族名称
     *
     * @param id
     * @param familyName
     */
    public void saveFamilyName(Integer id, String familyName) {
        ArrayList<Object> list = new ArrayList<>();
        String sql = "update app_family set familyname=? where id=?";
        list.add(familyName);
        list.add(id);
        this.update(sql, list);
    }


    public void saveFamilyStatus(Integer id, Integer status) {
        ArrayList<Object> list = new ArrayList<>();
        String sql = "update app_family set status=? where id=?";
        list.add(status);
        list.add(id);
        this.update(sql, list);
    }


    public List<AppFamily> getAfterFamilyList(SplitPageBean splitPageBean, AppFamily appFamily) {
        ArrayList<Object> list = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select * from app_family where 1=1");
        if (StringEx.isNotNull(appFamily.getFamilyid())) {
            stringBuilder.append(" and familyid=?");
            list.add(appFamily.getFamilyid());
        }
        if (StringEx.isNotNull(appFamily.getStatus())) {
            stringBuilder.append(" and status=?");
            list.add(appFamily.getStatus());
        }
        if (StringEx.isNotNull(appFamily.getFamilyname())) {
            stringBuilder.append(" and familyname like '%" + appFamily.getFamilyname() + "%'");
//            list.add(appFamily.getFamilyname());
        }
        if (StringEx.isNotNull(appFamily.getBeginTime()) && StringEx.isNotNull(appFamily.getEndTime())) {
            stringBuilder.append(" and createtime>=? and createtime<=?");
            list.add(appFamily.getBeginTime());
            list.add(appFamily.getEndTime());
        }
        if (StringEx.isNotNull(appFamily.getLeaderPhone())) {
            AppUser byLoginname = appUserDao.findByLoginname(appFamily.getLeaderPhone());
            if (byLoginname != null) {
                stringBuilder.append(" and leaderid=?");
                list.add(byLoginname.getId());
            }
        }
        stringBuilder.append(" order by createtime desc");
        String sql = stringBuilder.toString();
        return this.queryList(sql, list, AppFamily.class, splitPageBean);
    }

    public void verifyFamily(AppFamily appFamily) {
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<Object> list = new ArrayList<>();
        if (appFamily.getVerifyType() == 1) {
            stringBuilder.append("update app_family set status=? where id=?");
            list.add(0);
            list.add(appFamily.getId());
        } else if (appFamily.getVerifyType() == 2) {
            stringBuilder.append("update app_family set status=?,refuseText=? where id=?");
            list.add(4);
            list.add(appFamily.getRefuseText());
            list.add(appFamily.getId());
        }
        String sql = stringBuilder.toString();
        this.update(sql, list);
    }

    public AppFamily findByFamilyId(Integer familyId) {
        String sql = "select * from app_family where familyid=" + familyId;
        return this.queryObj(sql, null, AppFamily.class);
    }


}
